<template>
  <uv-upload
    :fileList="fileList"
    :multiple="multiple"
    @afterRead="afterRead"
    :accept="accept"
    @delete="deletePic"
    width="180rpx"
    height="180rpx"
    v-bind="$attrs"
  >
    <slot>
      <view class="upload df-cc" :class="customClass">
        <!-- <k-image
          width="50rpx"
          height="50rpx"
          :src="$TOOL.url('/business/icons/upload.png')"
        ></k-image> -->
        <text
          class="custom-icon custom-icon-tianjiatupian ft-30 text-less-color-1"
        ></text>
      </view>
    </slot>
  </uv-upload>
</template>

<script setup>
// 此处为默认扩展文档地址：https://www.uvui.cn/components/upload.html
import { onMounted, ref, watch } from "vue";
import { isArray, isFunction } from 'lodash';
import utils from "@/utils";
import { uploadFilePromise } from '@/hooks/app';
// import KImage from "@/components/k-image/k-image";

const props = defineProps({
  modelValue: {
    type: [Array, String],
    default: () => [],
  },
  accept: {
    type: String,
    default: 'image',
  },
  customClass: {
    type: String,
    default: 'image',
  },
  multiple: {
    type: Boolean,
    default: false,
  },
  beforeDelete: {
    type: Function,
    default() {
      return new Promise((resolve, reject) => {
        uni.showModal({
          title: "温馨提示",
          content: "是否删除该图片？",
          success: (res) => {
            if (res.confirm) {
              resolve(true);
            } else {
              reject();
            }
          },
        });
      });
    },
  },
});
const emit = defineEmits(['update:modelValue']);
const isArrValue = isArray(props.modelValue);
const fileList = ref([]);

/** 初始化 */
const initData = () => {
  if (isArrValue) {
    fileList.value = props.modelValue.map((url) => {
      return {
        status: 'success',
        message: '',
        url: utils.urlFilter(url),
        realUrl: url,
      };
    });
  } else {
    fileList.value = props.modelValue
      ? [
          {
            status: 'success',
            message: '',
            url: utils.urlFilter(props.modelValue),
            realUrl: props.modelValue,
          },
        ]
      : [];
  }
  console.log(fileList.value);
};
onMounted(initData);
watch(
  () => props.modelValue,
  () => {
    initData();
  }
);
/**
 * 上传成功后回调
 * @param event
 */
const afterRead = async (event) => {
  const lists = [].concat(props.multiple ? event.file : [event.file]);
  let fileListLen = fileList.value.length;
  lists.map((item) => {
    fileList.value.push({
      ...item,
      status: 'uploading',
      message: '上传中',
    });
  });
  for (let i = 0; i < lists.length; i++) {
    const result = await uploadFilePromise(lists[i].url, props.accept);
    const item = fileList.value[fileListLen];
    fileList.value.splice(
      fileListLen,
      1,
      Object.assign(item, {
        status: 'success',
        message: '',
        url: item.thumb || utils.urlFilter(result),
        realUrl: result,
      })
    );
    fileListLen++;
  }
  updateValue();
};
const beforeRead = () => {
  console.log('1');
};
/**
 * 删除图片
 * @param index
 */
const deletePic = async (index) => {
  if (isFunction(props.beforeDelete)) {
    await props.beforeDelete(fileList.value, index);
  }
  fileList.value.splice(index, 1);
  updateValue();
};

/**
 * 更新图片
 */
const updateValue = () => {
  const emitVal = isArrValue
    ? fileList.value.map((item) => item.realUrl)
    : fileList.value.map((item) => item.realUrl)[0];
  emit('update:modelValue', emitVal);
};
</script>

<style scoped lang="scss">
.upload {
  width: 200rpx;
  height: 200rpx;
  border-radius: 20rpx 20rpx 20rpx 20rpx;
  background: rgba(237, 237, 237, 0.5);
}
</style>
